/**
 * File: BucketSubmitController.java
 * Created by: mhaimel
 * Created on: 23 Jul 2009
 * CVS:  $Id: BucketSubmitController.java,v 1.3 2009/10/09 14:46:32 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.general;

import java.io.File;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;

import uk.ac.ebi.curtain.controller.SingleSubmitController;
import uk.ac.ebi.curtain.util.FileHelper;
import uk.ac.ebi.velvet.model.Supercontig;

/**
 * @author mhaimel
 *
 */
public class BucketSubmitController extends SingleSubmitController<Serializable,File> {

	private static final String TEST_dir = "test";

	@Override
	protected void singleSubmit(List<Serializable> inputList) {
		File baseDir = getContext().currentFiles().getBucketDir();
		if(!getContext().getArguments().getBatchList().isEmpty()){
			List<Integer> batchList = getContext().getArguments().getBatchList();
			_submitRange(baseDir,batchList);
		} else {
			_submitAll(baseDir);
		}
	}

	private void _submitAll(File baseDir) {		
		Stack<File> stack = new Stack<File>();
		stack.add(baseDir);
		
		while(!stack.isEmpty()){
			File dir = stack.pop();
			Set<File> tmpFiles = new HashSet<File>();
			boolean isBucket = false;
			for(File f : dir.listFiles()){
				if(f.isDirectory() && !f.getName().equals(TEST_dir)){
					tmpFiles.add(f);
				} else {
					if(f.getName().equals(Supercontig.FILE_SUMMARY)){
						isBucket = true;
						break;
					}
					if(f.getName().equals(Supercontig.FILE_NODE_ID)){
						isBucket = true;
						break;
					}
				}
			}
			if(isBucket){
				// found summary
				submit(dir);
			} else {
				stack.addAll(tmpFiles);
			}
		}
		getLog().debug("Finished submitting");
	}

	private void _submitRange(File baseDir, List<Integer> batchList) {
		for(Integer id : batchList){
			if(null != id){
				File subDir = FileHelper.getSubDirectory(baseDir, id);
				if(subDir.exists()){
					submit(subDir);
				}
			}
		}
	}	
}
